#include "output.h"
#include "myserialport/spscaleadaptor.h"
#include <QDebug>

Output::Output(int no):mNo(no),mContinueTimer(nullptr)
{

}

void Output::setNormalStatus(uint status)
{
    mNormalStatus = status;
     qDebug()<<".........setNormalStatus.........."<<status<<"curr"<<mStatus;
    __setStatus(mStatus);

}


void Output::setRange(float lo,float hi)
{
    mData.range.hi = hi;
    mData.range.lo = lo;
}

void Output::setPoint(float p)
{
     mData.point = p;
}

void Output::checkPoint(float w)
{
    if(mData.point>w)
       this->setStatus(Output::SET);
    else
       this->setStatus(Output::RESET);
}

bool Output::checkRange(float w)
{
    if(w>=mData.range.lo && w<=mData.range.hi)
    {
       this->setStatus(Output::SET);
       return true;
    }
    else
    {
       this->setStatus(Output::RESET);
       return false;
    }
}

void Output::setStatus(Output::Status status)
{
    if(status==UNKNOW) return;

    //qDebug()<<"want set status"<<mIOnum<<status<<QTime::currentTime().second();
    if(mDelayTime==0)
    {
        if(status==SET){
           startStatusSet();
        }
        else if(mContinueTime==0){ //持续时间为0,以实际触发为准。
           endStatusSet();
        }
    }
    else
    {
        if(status==SET){
            QTimer::singleShot(mDelayTime,this,SLOT(startStatusSet()));
        }else{
            if(mContinueTime==0){
                QTimer::singleShot(mDelayTime,this,SLOT(endStatusSet()));
            }
        }
    }

}

void Output::startStatusSet()
{
    __setStatus(SET);
    if(mContinueTime!=0){
        if(mContinueTimer == nullptr){
            mContinueTimer = new QTimer(this);
            mContinueTimer->setSingleShot(true);
            connect(mContinueTimer,SIGNAL(timeout()),this,SLOT(endStatusSet()));
        }
        mContinueTimer->start(mContinueTime);
    }
}

void Output::endStatusSet()
{
    __setStatus(RESET);
}

void Output::__setStatus(Status status)//最底层的
{
    mStatus = status;
    if(status == SET)
    {
        //qDebug()<<"set status"<<mIOnum<<status<<QTime::currentTime().second()<<!(mNormalStatus);
        //gpio_write(mIOnum,!(mNormalStatus));
        SpScaleAdaptor::getInstance()->setOutput(mNo,mNormalStatus);
    }
    else if(status == RESET)
    {
//        qDebug()<<"set status"<<mIOnum<<status<<QTime::currentTime().second()<<mNormalStatus;
//        gpio_write(mIOnum,mNormalStatus);
        SpScaleAdaptor::getInstance()->setOutput(mNo,!(mNormalStatus));
    }
}
